<script setup>
/**
 * & 文件引入区域
 */

import { useRoute, useRouter } from "vue-router";
import { onBeforeMount, onMounted, ref } from "vue";

import {
  getShopCategorySecList,
  getSecShopInfoList,
  getShopInfoMinList,
} from "@/server/api/shopApi";

import { shopStore } from "@/stores/shop";
import { useUseStore } from "@/stores/user";
import { useIndexStore } from "@/stores/indexStore";

import { initMap, getDistance, getLocation } from "@/utils/mapHandle";
import { ToastFun } from "@/hook/toast";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
/**
 * & 注册区
 */

/**
 * & 变量声明区
 */
const router = useRouter();
const route = useRoute();
const loading = ref(false); // 控制实体店列表加载
const finished = ref(false); // 实体店列表加载完毕
let baseUrl = useUseStore().ing; // 商品数据图片基础路径
let categoryShow = ref(true); // 控制分类列表显示隐藏
// 据条件筛选后获取实体店列表请求体
let SecShopInfoListReq = {
  limit: 10,
  pages: 1,
  categoryId: -1,
  regionId: useUseStore().regionId,
  shopName: "",
};
// 二级分类下全部实体店列表过滤请求体
let ShopInfoMinListReq = {
  limit: 10,
  pages: 1,
  categoryId: -1,
  regionId: useUseStore().regionId,
  shopName: "",
};
let SecShopInfoList = ref(); // 据条件筛选后获取实体店列表数据
let changeApi = ref(false); // 控制切换接口调用,和修改对应的请求体

/**
 * & 函数区
 */
// 跳转详情页方法
const toShopDetailsFun = (id) => {
  router.push({
    path: "/ShopDetail",
    query: {
      id,
    },
  });
};

// 获取实体店二级分类列表
const getShopCateSecListFun = async (id) => {
  ToastFun("Loading", { duration: 1000 });
  let { data } = await getShopCategorySecList(id);

  if (data.code == 200) {
    ToastFun("close", {});
    data.data.forEach(
      (item) => (item.categoryImg = baseUrl + item.categoryImg)
    );

    // shopStore().setCateFun(route.query.id, data.data);
    shopStore().ShopCateSecListData[route.query.id] = data.data;
    console.log(data.data);
    console.log(1111);
  } else {
    ToastFun("", {});
  }
};

// 根据条件筛选后获取实体店列表
const getSecShopInfoListFun = async (id) => {
  if (id) {
    SecShopInfoListReq.categoryId = id;
    SecShopInfoList.value = null;
  }

  // 不是第一次请求则页数自增
  SecShopInfoListReq.pages += SecShopInfoList.value != null ? 1 : 0;

  // 发起请求
  let res = await getSecShopInfoList(SecShopInfoListReq);
  let data = res.data.data;

  // 加载结束
  loading.value = false;

  // 如果大于等于总数,请求结束
  if (SecShopInfoListReq.pages * SecShopInfoListReq.limit >= data.count) {
    finished.value = true;
  }

  // 图片路径拼接，存入经纬度
  data.list.forEach((item) => {
    // let ImgList = item.userImage.split(".");
    // item.userImage = baseUrl + ImgList[0] + "_90_100." + ImgList[1];
    item.coords = [item.localhostLatitude, item.localhostLongitude];
  });

  // 如果数据为空,为第一次请求直接赋值,不为空则将请求的数据展开push进原数据的list
  SecShopInfoList.value == null
    ? (SecShopInfoList.value = data)
    : SecShopInfoList.value.list.push(...data.list);
  // console.log("当前分类全部实体店列表数据", SecShopInfoList.value);

  // 获取距离
  await getLocation();
  SecShopInfoList.value.list.forEach((item) => {
    item.distance = getDistance(item.coords);
  });
};

// 二级分类下全部实体店列表过滤
const getShopInfoMinListFun = async (id) => {
  if (id) {
    ShopInfoMinListReq.categoryId = id;
    SecShopInfoList.value = null;
    finished.value = false;
  }

  // 隐藏分类列表
  categoryShow.value = false;

  // 不是第一次请求则页数自增
  ShopInfoMinListReq.pages += SecShopInfoList.value != null ? 1 : 0;

  // 发起请求
  let res = await getShopInfoMinList(ShopInfoMinListReq);
  let data = res.data.data;

  // 加载结束
  loading.value = false;

  // 如果大于等于总数,请求结束
  if (ShopInfoMinListReq.pages * ShopInfoMinListReq.limit >= data.count) {
    finished.value = true;
  }

  data.list.forEach((item) => {
    // let ImgList = item.userImage.split(".");
    // item.userImage = baseUrl + ImgList[0] + "_90_100." + ImgList[1];
    item.coords = [item.localhostLatitude, item.localhostLongitude];
  });

  // 如果数据为空,为第一次请求直接赋值,不为空则将请求的数据展开push进原数据的list
  SecShopInfoList.value == null
    ? (SecShopInfoList.value = data)
    : SecShopInfoList.value.list.push(...data.list);
  console.log("当前分类全部实体店列表数据", SecShopInfoList.value);

  // 切换滚动加载的请求接口
  changeApi.value = true;

  // 获取距离
  await getLocation();
  SecShopInfoList.value.list.forEach((item) => {
    item.distance = getDistance(item.coords);
  });
};

// 判断调用哪个接口
const onload = () => {
  if (changeApi.value) {
    getShopInfoMinListFun();
  } else {
    getSecShopInfoListFun();
  }
};

// 返回分类页状态方法
const backCateFun = () => {
  // 显示分类框
  categoryShow.value = true;

  // 重新获取原来的数据
  changeApi.value = false; // 切换分页加载的请求接口
  SecShopInfoListReq.pages = 1; // 重回第一页
  getSecShopInfoListFun(route.query.id); // 发送请求

  // 重置加载状态
  finished.value = false;
};

// 模糊查询方法
const searchFun = (vl) => {
  // 判断修改哪个请求体
  if (changeApi.value) {
    ShopInfoMinListReq.shopName = vl;
    ShopInfoMinListReq.pages = 1;
    SecShopInfoList.value = null;
    getShopInfoMinListFun();
  } else {
    SecShopInfoListReq.shopName = vl;
    SecShopInfoListReq.pages = 1;
    SecShopInfoList.value = null;
    getSecShopInfoListFun();
  }
};

onBeforeMount(() => {
  // 获取实体店二级分类列表
  shopStore().ShopCateSecListData[route.query.id]
    ? ""
    : getShopCateSecListFun(route.query.id);
  getSecShopInfoListFun(route.query.id); // 根据条件筛选后获取实体店列表
  console.log(11111);
});

onMounted(() => {
  initMap();
});
</script>

<template>
  <div id="container"></div>

  <div class="CategoryPage">
    <div class="top">
      <TopBar :type="2" @searchFun="searchFun">
        <div class="backBtn" v-show="!categoryShow" @click="backCateFun">
          back
        </div>
      </TopBar>
    </div>

    <div class="categoryBox" v-if="shopStore().ShopCateSecListData[$route.query.id] && categoryShow">
      <div v-for="item in shopStore().ShopCateSecListData[$route.query.id]"
        @click="getShopInfoMinListFun(item.categoryId)" :key="item.categoryId" class="item">
        <img v-lazy="item.categoryImg" alt="" class="logo" />
        <div class="text cut-txt">{{ $t(`shopFirCate.${item.content}`) }}</div>
      </div>
    </div>

    <!-- <div class="selectBar">
      <SelectBox />
    </div> -->

    <div class="businessList" v-if="SecShopInfoList">
      <van-list :finished-text="$t('shop.shopList.finish')" v-model:loading="loading" :finished="finished"
        @load="onload" :offset="5">
        <div class="item" :key="item.shopId" v-for="item in SecShopInfoList.list"
          @click="toShopDetailsFun(item.shopId)">
          <div :class="['img', useIndexStore().isRtl ? 'is_rtl' : '']">
            <img v-lazy="item.userImage" alt="" class="logo" />
            <div class="PiLogo" v-show="item.membership">{{ item.piratio }}</div>
          </div>

          <div class="right">
            <div class="title">{{ item.shopName }}</div>

            <div class="sub">
              <span v-if="!item.shopTagsList">{{
                $t("shop.shopList.noData")
              }}</span>
              <span v-show="i < 4" v-for="(vl, i) in item.shopTagsList" :key="vl.tagId">
                {{ vl }}
                <span v-if="i < 3 && i < item.shopTagsList.length - 1">
                  |
                </span>
              </span>
            </div>

            <div class="address cut-txt-2">{{ item.address }}</div>

            <div class="score">
              <div class="start" v-if="item.score && item.score <= 5">
                <img src="/images/Shop/start1.png" alt="" v-for="item in parseInt(item.score)" :key="item" />
                <img src="/images/Shop/start2.png" v-for="item in 5 - parseInt(item.score)" :key="item" alt="" />
              </div>

              <div class="num">{{ item.score }}</div>
            </div>

            <div class="comment">
              {{ item.shopIntroduce || $t("shop.shopList.noData") }}
            </div>

            <div :class="['distance', useIndexStore().isRtl ? 'is_rtl' : '']">
              {{ item.distance || $t("shop.shopList.noPosition") }}
            </div>
          </div>
        </div>
      </van-list>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.CategoryPage {
  position: relative;
  background: #f5f5f5;

  min-height: 100vh;
  max-height: 100vh;
  overflow-y: scroll;

  &::-webkit-scrollbar {
    display: none;
  }

  >.top {
    padding: 0 16rem;
    background: #f5f5f5;
    position: sticky;
    top: 0;
    z-index: 100;

    .backBtn {
      background: #dddddd;
      padding: 5rem 8rem;
      border-radius: 5rem;
      margin-right: 5rem;

      color: #333333;
    }

    :deep(.topBar) {
      padding: 16rem 0;

      >.search {
        margin-left: 34rem;
        margin-right: 52rem;
        background-color: #e6e6e6;
      }
    }
  }

  >.categoryBox {
    background: #fff;
    padding: 12rem 16rem 0;
    margin-bottom: 12rem;

    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    >.item {
      margin-bottom: 12rem;
      // margin-right: 34rem;
      width: 60rem;

      &:nth-of-type(5n) {
        margin-right: 0;
      }

      >img {
        width: 44rem;
        margin: 0 auto;
        margin-bottom: 4rem;
        display: block;
      }

      >.text {
        font-size: 14rem;
        font-weight: 400;
        letter-spacing: 0rem;
        line-height: 16rem;
        color: rgba(102, 102, 102, 1);
        text-align: center;
      }
    }
  }

  >.selectBar {
    background: #f5f5f5;
    padding-top: 16rem;
    position: sticky;
    top: 64rem;
    z-index: 100;

    :deep(.selectBox) {
      background-color: unset;
      margin-bottom: 4rem;
      padding-right: 0;

      >.content .item {
        background: #fff;
        color: #666;
      }
    }
  }

  >.businessList {
    .item {
      position: relative;
      padding: 12rem 16rem;
      background: #fff;
      border-bottom: 1rem solid #e6e6e6;

      display: flex;

      >.img {
        width: 86rem;
        min-width: 86rem;
        height: 100rem;
        margin-right: 12rem;
        border-radius: 8rem;

        position: relative;

        overflow: hidden;

        &.is_rtl {
          margin-left: 12rem;
          margin-right: 0;
        }

        >img {
          width: 100%;
          height: 100%;
        }

        >.PiLogo {
          position: absolute;
          left: 0;
          top: 0;

          padding: 1rem 12rem;

          font-size: 14rem;
          font-weight: 500;
          line-height: 20rem;
          color: #fff;

          background: #642e8e;
          border-radius: 8rem 0rem 8rem 0rem;
        }
      }

      >.right {
        font-weight: 400;
        color: #999;
        line-height: 16rem;
        font-size: 12rem;

        >.title {
          color: #333333;
          font-size: 16rem;
          line-height: 16rem;
          font-weight: 500;
          margin-bottom: 4rem;
        }

        >.sub {
          color: #666;
          font-size: 14rem;
          line-height: 16rem;
          margin-bottom: 4rem;
          padding-right: 10rem;

          width: 100%;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }

        >.score {
          display: flex;
          align-items: center;
          margin: 10rem 0 5rem;

          >.start {
            display: flex;
            align-items: center;

            >img {
              margin-right: 2rem;
            }
          }

          >.num {
            font-size: 13rem;
            line-height: 16rem;
            font-weight: 500;
            color: #666666;
            margin-left: 10rem;
          }
        }

        >.distance {
          position: absolute;
          right: 16rem;
          bottom: 12rem;

          &.is_rtl {
            right: unset;
            left: 16rem;
          }
        }
      }
    }
  }
}
</style>
